package cn.roadtrip.utilmodule;

import cn.hutool.core.codec.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

@SpringBootTest
public class WechatDecryptUtil {

    static {
        //BouncyCastle作为安全提供，防止我们加密解密时候因为jdk内置的不支持改模式运行报错。
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 微信小程序公共信息解密
     *
     * @param encryptedData
     * @param sessionKey
     * @param iv
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedData, String sessionKey, String iv) throws Exception {
        byte[] dataByte = Base64.decode(encryptedData);
        byte[] keyByte = Base64.decode(sessionKey);
        byte[] ivByte = Base64.decode(iv);

        // 如果密钥不足16位，那么就补足。这个if 中的内容很重要
        int base = 16;
        if (keyByte.length % base != 0) {
            int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
            keyByte = temp;
        }

        // 生成iv
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
        parameters.init(new IvParameterSpec(ivByte));

        // 解密
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
        byte[] resultByte = cipher.doFinal(dataByte);

        if (null != resultByte && resultByte.length > 0) {
            return new String(resultByte, "UTF-8");
        }
        return null;
    }


    @Test
    void contextLoads() throws Exception {
        String rs = decrypt(
                "k1iH3UZHVE1w3xFZ/WRHzlwc3Gl54LTBtZeMsfqpqvYm8IayyqxRgbBgOLBhCE1yE5fCfa6I6v5Xzc6QS1q4MgcTtqvFtOxnBceooxQ4Ftbs2ceTQoQW7838Mh5rEmZ94ZPGpZryiUhUD9z1gMZ3bQmQvMYoJ/dg2Z8jwwISeSGJP9peLhP/SDru2v5ajIEIH7rSKW3u3LlRZCOMAJwqNq9503NRt5Wx4jwM3U9TRCxHikRaYv8q3GmpiV3wQ/W2jVe/c/3LK+jg8YHcG6wp/ZtP+DBl7weSo+EE8WqpfL17BqmumbkydfEoFRhacg0/LMk6zZZupVZSOFuteO8n5M6fYAjwuB1bf5OMU4mynrPyjcHFtiaptxf+asM6bGMWno7aYuN2hCvTpEJB2YBu1dQl0ZGur8jxPDMA2LpJPeO9Uvl+7rGGqLpT75c+dphN",
                "WGIltR1uAEa26sgzSniCmg==",
                "TC3cRc+NplUqFHHS77qcxw==");
        System.out.println(rs);
    }
}